package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.LinkedHashSet;

/**
 * @author ace
 * @create 2018/3/12.
 */
@Configuration
@Slf4j
public class AccessGatewayFilter implements GlobalFilter{
    /**
     * 不处理的请求前缀
     */
    private static final String START_WITH = "api,de,hao";
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            log.info("check token and user permission....");
            LinkedHashSet requiredAttribute = exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
            ServerHttpRequest request = exchange.getRequest();
            String requestUri = request.getPath().pathWithinApplication().value();
            final String method = request.getMethod().toString();
            ServerHttpRequest.Builder mutate = request.mutate();

//            String token = exchange.getRequest().getQueryParams().getFirst("authToken");

            // token不存在
//            if (token == null || token.isEmpty()) {
//                return setFailedRequest(exchange,"",401);
//            }

            // 不进行拦截的地址
            if (isStartWith(requestUri)) {
                ServerHttpRequest build = mutate.build();
                return chain.filter(exchange.mutate().request(build).build());
            }

            ServerHttpRequest build = mutate.build();
            return chain.filter(exchange.mutate().request(build).build());
        }

        /**
         * URI是否以什么打头
         *
         * @param requestUri
         * @return
         */
        private boolean isStartWith(String requestUri) {
            boolean flag = false;
            for (String s : START_WITH.split(",")) {
                if (requestUri.startsWith(s)) {
                    return true;
                }
            }
            return flag;
        }

        /**
         * 网关抛异常
         *
         * @param body
         * @param code
         */
        private Mono<Void> setFailedRequest(ServerWebExchange serverWebExchange, String body, int code) {
            serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
            return serverWebExchange.getResponse().setComplete();
        }

    /**
     * 网关抛异常
     *
     * @param body
     */
//    @NotNull
//    private Mono<Void> getVoidMono(ServerWebExchange serverWebExchange, BaseResponse body) {
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
//        byte[] bytes = JSONObject.toJSONString(body).getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = serverWebExchange.getResponse().bufferFactory().wrap(bytes);
//        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
//    }
}
